import { ref, onUnmounted } from 'vue';
import { Client } from '@stomp/stompjs';
import { useUserStore } from '@/stores';

const userStore = useUserStore();

export default function useStomp(brokerURL, handleMessageFunction) {
  // 响应式状态管理
  const client = ref(null);
  const isConnected = ref(false);
  const messageArray = ref([]);
  const error = ref(null);

  // 初始化连接
  const connect = (subscribePath) => {
    const socket = new WebSocket(brokerURL);
    client.value = new Client({
      webSocketFactory: () => socket,
      reconnectDelay: 5000, // 自动重连间隔
      connectHeaders: {
        Authorization: `Bearer ${userStore.token}` // 添加Token认证头
      },
      onConnect: () => {
        isConnected.value = true;
        error.value = null;
        if (subscribePath) {
          subscribe(subscribePath);
        }
      },
      onStompError: (frame) => {
        error.value = `STOMP错误: ${frame.headers.message}`;
        console.log(error.value)
      }
    });
    
    client.value.activate(); // 启动连接
  };

  // 订阅消息
  const subscribe = (destination) => {
    if (!client.value || !isConnected.value) return;
    
    return client.value.subscribe(destination, (message) => {
      if (handleMessageFunction) {
        handleMessageFunction(message);
      }
    });
  };

  // 发送消息
  const send = (destination, body) => {
    if (isConnected.value) {
      client.value.publish({
        destination,
        body: JSON.stringify(body)
      });
    }
  };

  // 断开连接
  const disconnect = () => {
    if (client.value) {
      client.value.deactivate();
      isConnected.value = false;
    }
  };

  // 组件卸载时自动断开连接
  onUnmounted(() => {
    disconnect();
  });

  // 暴露状态和方法
  return {
    isConnected,
    messageArray,
    error,
    connect,
    subscribe,
    send,
    disconnect
  };
}